package cn.com.shopec.erp.product.commo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import cn.com.shopec.erp.base.dao.IProfitsProductDao;
import cn.com.shopec.erp.base.entity.ProfitsProduct;
import cn.com.shopec.erp.base.entity.ProfitsProductHistory;
import cn.com.shopec.erp.base.service.IProfitsService;
import cn.com.shopec.erp.common.page.PageFinder;
import cn.com.shopec.erp.common.utils.DateUtil;
import cn.com.shopec.erp.common.utils.LogicUtil;
import cn.com.shopec.erp.common.utils.StringUtil;
import cn.com.shopec.erp.product.controller.CommodityController;
import cn.com.shopec.erp.product.dao.IBrandDao;
import cn.com.shopec.erp.product.dao.ICommodityCatDao;
import cn.com.shopec.erp.product.dao.ICommodityDao;
import cn.com.shopec.erp.product.dao.IProdSpecValueDao;
import cn.com.shopec.erp.product.dao.IProductInventoryDao;
import cn.com.shopec.erp.product.dao.ISpecValOptionDao;
import cn.com.shopec.erp.product.entity.Brand;
import cn.com.shopec.erp.product.entity.Commodity;
import cn.com.shopec.erp.product.entity.CommodityCat;
import cn.com.shopec.erp.product.entity.ProdSpecValue;
import cn.com.shopec.erp.product.entity.Product;
import cn.com.shopec.erp.product.entity.ProductHistory;
import cn.com.shopec.erp.product.entity.ProductInventory;
import cn.com.shopec.erp.product.entity.SpecValOption;
import cn.com.shopec.erp.product.model.BenefitProduct;
import cn.com.shopec.erp.product.vo.CommodityVo;
import cn.com.shopec.erp.product.vo.ProductHistoryVo;
import cn.com.shopec.erp.product.vo.ProductVo1;

/**
 * 
 * @ClassName ProductVoConvertor
 * @Description 商品货品对象转换器
 * @author duhui
 * @date 2013-5-20 下午7:00:24
 */
@Component
public class ProductVoConvertor {

    @Resource
    private IProdSpecValueDao prodSpecValueDao;

    @Resource
    private ISpecValOptionDao specValOptionDao;

    @Resource
    private ICommodityDao commodityDao;

    @Resource
    private IBrandDao brandDao;

    @Resource
    private ICommodityCatDao commodityCatDao;

    @Resource
    private IProductInventoryDao productInventoryDao;

    @Resource
    private IProfitsProductDao profitsProductDao;
    
    @Resource
    private IProfitsService profitsService;
    
    @Resource
    private CommodityVoConvertor commodityVoConvertor;

    /**
     * 
     * @Title: convert2ProductVo
     * @Description: productHistory转productHistoryVo
     * @return
     * @throws
     * @author: duhui
     * @date: 2013-5-23上午09:40:37
     */
    public ProductHistoryVo convert2ProductHistoryVo(ProductHistory productHistory) {
        ProductHistoryVo productHistoryVo = null;

        if (LogicUtil.isNotNull(productHistory)) {
            productHistoryVo = new ProductHistoryVo();

            productHistoryVo.setOpType(productHistory.getOpType());
            productHistoryVo.setOpTime(productHistory.getOpTime());
            productHistoryVo.setOpPerson(productHistory.getOpPerson());
            productHistoryVo.setOldQuantity(productHistory.getOldQuantity());
            productHistoryVo.setOpQuantity(productHistory.getOpQuantity());

            long newQuantity = 0;// 操作后的库存数量
            if (LogicUtil.isNotNull(productHistoryVo.getOldQuantity())
                    && LogicUtil.isNotNull(productHistoryVo.getOpQuantity())) {
                newQuantity = productHistoryVo.getOldQuantity().longValue()
                        + productHistoryVo.getOpQuantity().longValue();
            }
            productHistoryVo.setNewQuantity(newQuantity);

        }

        return productHistoryVo;

    }

    /**
     * 
     * @Title: convert2BaseProduct
     * @Description: productHistoryVo转productHistory
     * @param productHistoryVo
     * @return
     * @throws
     * @author: duhui
     * @date: 2013-5-23上午10:04:53
     */
    public ProductHistory convert2BaseProductHistory(ProductHistoryVo productHistoryVo) {
        ProductHistory productHistory = null;

        if (LogicUtil.isNotNull(productHistoryVo)) {
            productHistory = new ProductHistory();

            productHistory.setgNo(productHistoryVo.getgNo());
            productHistory.setOpType(productHistoryVo.getOpType());
            productHistory.setOpTime(productHistoryVo.getOpTime());
            productHistory.setOpPerson(productHistoryVo.getOpPerson());
            productHistory.setOldQuantity(productHistoryVo.getOldQuantity());
            productHistory.setOpQuantity(productHistoryVo.getOpQuantity());
            productHistory.setDeleteFlag(productHistoryVo.getDeleteFlag());

        }

        return productHistory;
    }

    /**
     * 
     * @Title: convert2BenefitProduct
     * @Description: Product转BenefitProduct
     * @param benefitProduct
     * @return
     * @throws
     * @author: duhui
     * @date: 2013-7-2下午05:37:29
     */
    public BenefitProduct convert2BenefitProduct(Product product) {
        BenefitProduct benefitProduct = null;

        if (LogicUtil.isNotNull(product)) {
            benefitProduct = new BenefitProduct();

            benefitProduct.setProdNo(product.getProdNo());
            benefitProduct.setCasePakgSize(product.getCasePakgSize());
            benefitProduct.setInventoryType(product.getInventoryType());
            benefitProduct.setProdBarCode(product.getProdBarCode());
            benefitProduct.setSalePrice(product.getSalePrice());
            benefitProduct.setSaleType(product.getSaleType());

            Commodity commodity = this.commodityDao.findUniqueBy("commoNo", product.getCommoNo());
            if (LogicUtil.isNotNull(commodity)) {
                benefitProduct.setCommoName(commodity.getCommoName());
                benefitProduct.setCommoNo(commodity.getCommoNo());
                benefitProduct.setBrandNo(commodity.getBrandNo());
                benefitProduct.setCatNo(commodity.getCatNo());

                CommodityCat commodityCat = this.commodityCatDao.findUniqueBy("catNo", commodity.getCatNo());
                if (LogicUtil.isNotNull(commodityCat)) {
                    benefitProduct.setCatName(commodityCat.getCatName());
                }

                Brand brand = this.brandDao.findUniqueBy("brandNo", commodity.getBrandNo());
                if (LogicUtil.isNotNull(brand)) {
                    benefitProduct.setBrandName(brand.getBrandName());
                }

                /** 设置货品总库存 **/
                int prodNum=0; //货品总库存
                List<ProductInventory>  productInventorys = this.productInventoryDao.findByProperty("prodNo", product.getProdNo());
                if (LogicUtil.isNotNullAndEmpty(productInventorys)) {
                	for(ProductInventory prodInventory:productInventorys){
                		prodNum+=prodInventory.getQuantity();
                	}
                }
                benefitProduct.setProductQuantity(prodNum);
            }

            ProfitsProduct profitsProduct = this.profitsProductDao.findUniqueBy("productCode", product.getProdNo());
            if (null != profitsProduct) {
                ProfitsProductHistory pph = this.profitsService.getLastHistory(profitsProduct, 1);
                if (null != pph) {
                    Long tom = DateUtil.getMillis(DateUtil.parseDate(pph.getValidTimeEnd() + " 12:00:00",
                            DateUtil.TIMESTAMP_PATTERN)) + (24 * 60 * 60 * 1000);
                    String tomorrow = DateUtil.formatDateByFormat(new Date(tom), DateUtil.DEFAULT_PATTERN);
                    benefitProduct.setTomorrow(tomorrow);
                } else {
                    ProfitsProductHistory pph0 = this.profitsService.getLastHistory(profitsProduct, 0);
                    if (null != pph0) {
                        Long tom = DateUtil.getMillis(DateUtil.parseDate(pph0.getValidTimeEnd() + " 12:00:00",
                                DateUtil.TIMESTAMP_PATTERN)) + (24 * 60 * 60 * 1000);
                        String tomorrow = DateUtil.formatDateByFormat(new Date(tom), DateUtil.DEFAULT_PATTERN);
                        benefitProduct.setTomorrow(tomorrow);
                    } else {
                        benefitProduct.setTomorrow("");
                    }
                }

                Long current = DateUtil.getCurrentMillis();
                Long start = 0L;
                Long end = 0L;
                if (StringUtil.isExist(profitsProduct.getValidTimeStart())) {
                    start = DateUtil.getMillis(DateUtil.parseDate(profitsProduct.getValidTimeStart() + " 00:00:00",
                            DateUtil.TIMESTAMP_PATTERN));
                }
                if (StringUtil.isExist(profitsProduct.getValidTimeStart())) {
                    end = DateUtil.getMillis(DateUtil.parseDate(profitsProduct.getValidTimeEnd() + " 23:59:59",
                            DateUtil.TIMESTAMP_PATTERN));
                }
                if (start <= current && current <= end) {
                    benefitProduct.setEnable(1); // 不可编辑
                } else {
                    benefitProduct.setEnable(0); // 可编辑
                }
                benefitProduct.setSelected(profitsProduct.getSelected());
                benefitProduct.setOriginalCost(profitsProduct.getOriginalCost());
                benefitProduct.setOriginalRetailCost(profitsProduct.getOriginalRetailCost());
                if (profitsProduct.getOriginalCost() > 0 && profitsProduct.getOriginalRetailCost() > 0) {
                    benefitProduct.setOriginalRate(profitsProduct.getOriginalCost()
                            * profitsProduct.getOriginalRetailCost());
                }
                benefitProduct.setPromotionsCost(profitsProduct.getPromotionsCost());
                benefitProduct.setPromotionsRetailCost(profitsProduct.getPromotionsRetailCost());
                if (profitsProduct.getPromotionsCost() > 0 && profitsProduct.getPromotionsRetailCost() > 0) {
                    benefitProduct.setPromotionsRate(profitsProduct.getPromotionsCost()
                            * profitsProduct.getPromotionsRetailCost());
                }
                benefitProduct.setValidTimeStart(null == profitsProduct.getValidTimeStart() ? "" : profitsProduct
                        .getValidTimeStart());
                benefitProduct.setValidTimeEnd(null == profitsProduct.getValidTimeEnd() ? "" : profitsProduct
                        .getValidTimeEnd());
            } else {
                String tomorrow = DateUtil.formatDateByFormat(new Date(), DateUtil.DEFAULT_PATTERN);
                benefitProduct.setTomorrow(tomorrow);
                benefitProduct.setSelected(0);
                benefitProduct.setValidTimeStart("");
                benefitProduct.setValidTimeEnd("");
            }
        }

        return benefitProduct;
    }

    public List<BenefitProduct> convert2BenefitProducts(List<Product> products) {
        List<BenefitProduct> benefitProdcuts = null;

        if (LogicUtil.isNotNullAndEmpty(products)) {
            benefitProdcuts = new ArrayList<BenefitProduct>();

            for (Product product : products) {
                BenefitProduct benefitProduct = this.convert2BenefitProduct(product);
                benefitProdcuts.add(benefitProduct);
            }

        }

        return benefitProdcuts;
    }

    public PageFinder<BenefitProduct> convert2PagedBenefitProducts(PageFinder<Product> pagedProducts) {
        PageFinder<BenefitProduct> pagedBenefitProduct = null;

        if (LogicUtil.isNotNullAndEmpty(pagedProducts.getData())) {
            List<BenefitProduct> benefitProducts = this.convert2BenefitProducts(pagedProducts.getData());

            pagedBenefitProduct = new PageFinder<BenefitProduct>(pagedProducts.getPageNo(),
                    pagedProducts.getPageSize(), pagedProducts.getRowCount(), benefitProducts);

        }

        return pagedBenefitProduct;
    }

    /**
     * 
     * @Title: convertProductsVo
     * @Description: productHistorys转productHistoryVos
     * @param productHistorys
     * @return
     * @throws
     * @author: duhui
     * @date: 2013-5-23上午10:14:10
     */
    public List<ProductHistoryVo> convertProductsVo(List<ProductHistory> productHistorys) {
        List<ProductHistoryVo> productHistoryVos = null;

        if (LogicUtil.isNotNullAndEmpty(productHistorys)) {
            productHistoryVos = new ArrayList<ProductHistoryVo>();

            for (ProductHistory productHistory : productHistorys) {

                ProductHistoryVo productHistoryVo = this.convert2ProductHistoryVo(productHistory);
                productHistoryVos.add(productHistoryVo);
            }

        }

        return productHistoryVos;
    }

    /**
     * 
     * @Title: convert2ProductHistory
     * @Description: 将分页中的
     * @param pagedProductHistorys
     * @return
     * @throws
     * @author: duhui
     * @date: 2013-5-23上午10:35:04
     */
    public PageFinder<ProductHistoryVo> convert2ProductHistory(PageFinder<ProductHistory> pagedProductHistorys) {
        PageFinder<ProductHistoryVo> pagedProductHistoryVos = null;

        if (LogicUtil.isNotNullAndEmpty(pagedProductHistorys.getData())) {

            List<ProductHistoryVo> productHistoryVos = this.convertProductsVo(pagedProductHistorys.getData());

            pagedProductHistoryVos = new PageFinder<ProductHistoryVo>(pagedProductHistorys.getPageNo(),
                    pagedProductHistorys.getPageSize(), pagedProductHistorys.getRowCount(), productHistoryVos);

        }

        return pagedProductHistoryVos;
    }

    /**
     * @Title: convert2ProductVo
     * @Description: 货品实体转vo
     * @param product
     * @return
     * @throws
     */
    public ProductVo1 convert2ProductVo(Product product) {
        ProductVo1 productVo = null;

        if (LogicUtil.isNotNull(product)) {
            productVo = new ProductVo1();

            productVo.setCommoNo(product.getCommoNo());
            productVo.setProdNo(product.getProdNo());
            productVo.setProdBarCode(product.getProdBarCode());
            productVo.setSaleType(product.getSaleType());
            productVo.setSalePrice(product.getSalePrice());
            productVo.setInventoryType(product.getInventoryType());
            productVo.setCasePakgSize(product.getCasePakgSize());
            productVo.setUnSalePrice(product.getUnSalePrice());
            productVo.setProdRate(product.getProdRate());
            productVo.setBuyNum(product.getBuyNum());
            productVo.setProdUnit(product.getProdUnit());
            
            Commodity commodity = this.commodityDao.findUniqueBy("commoNo", product.getCommoNo());
            if(LogicUtil.isNotNull(commodity)){
            	CommodityVo commodityVo=this.commodityVoConvertor.convert2BaseCommodityVo(commodity);
            	productVo.setCommoName(commodityVo.getCommoName());
            	productVo.setBrandName(commodityVo.getBrandName());
            	productVo.setCatName(commodityVo.getCatName());
            }
          
			String specStrs = ""; // 拼装规格值信息
			List<ProdSpecValue> prodSpecValues = this.prodSpecValueDao.findByProperty("prodNo", product.getProdNo());
			if (LogicUtil.isNotNullAndEmpty(prodSpecValues)) {
				for (ProdSpecValue prodSpecValue : prodSpecValues) {
					SpecValOption specValOption = this.specValOptionDao.findUniqueBy("optionNo",prodSpecValue.getValOptionNo());
					specStrs += specValOption.getOptionName() + " ";
				}
			}
			productVo.setOptionNames(specStrs.trim().replace(" ", ","));

        }

        return productVo;
    }

    /**
     * 
     * @Title: convert2ProductVoList
     * @Description: 将products转为productVos
     * @param
     * @return
     * @throws
     */
    public List<ProductVo1> convert2ProductVoList(List<Product> products) {
        List<ProductVo1> productVos = null;

        if (LogicUtil.isNotNull(products)) {
            productVos = new ArrayList<ProductVo1>();

            for (Product product : products) {
                ProductVo1 productVo = this.convert2ProductVo(product);
                productVos.add(productVo);
            }
        }

        return productVos;
    }

    /**
     * 
     * @Title: convert2PagedProductVoPageFinder
     * @Description: 将分页中的products转为productVos
     * @param pagedProducts
     * @return
     * @throws
     */
    public PageFinder<ProductVo1> convert2PagedProductVoPageFinder(PageFinder<Product> pagedProducts) {
        PageFinder<ProductVo1> pagedProductVos = null;

        if (LogicUtil.isNotNull(pagedProducts.getData())) {
            List<ProductVo1> productVos = this.convert2ProductVoList(pagedProducts.getData());

            pagedProductVos = new PageFinder<ProductVo1>(pagedProducts.getPageNo(), pagedProducts.getPageSize(),
                    pagedProducts.getRowCount(), productVos);

        }

        return pagedProductVos;
    }
}
